import argparse
import base64
import os
from flask import Flask, request, jsonify, render_template
from detect import run, main, parse_opt  # Assuming detect.py exists in the same directory as this script

app = Flask(__name__)

UPLOAD_FOLDER = './data/images'
SAVE_FOLDER = './runs/detect/exp'
global filename
global filepath
global resultpath

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    global filename
    global filepath
    global resultpath
    if request.method == 'POST':
        if 'file' not in request.files:
            return jsonify({'error': 'No file part'}), 400
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': 'No selected file'}), 400
        if file:
            filename = file.filename
            filepath = os.path.join(UPLOAD_FOLDER, filename)
            file.save(filepath)
            opt = parse_opt()  # Assuming parse_opt() function is defined in detect.py
            main(opt)  # Assuming main() function is defined in detect.py
            resultpath=os.path.join(SAVE_FOLDER, filename)
            img_stream = return_img_stream(resultpath)  # Get processed image stream
            return jsonify({'img_stream': img_stream})  # Return JSON response with image stream

    return render_template('index.html')

def return_img_stream(img_local_path):
    with open(img_local_path, 'rb') as img_f:
        img_stream = base64.b64encode(img_f.read()).decode()
    return img_stream

if __name__ == '__main__':
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
    app.run(host='0.0.0.0', port=5000)
